package real.bytedance.math;

import org.junit.Test;

public class BigNumberAdderIn36 {
    //36位大数加法：'0' ~ '9',数字0到9， 'a'~'z', 数字10到35
    public String add(String a, String b) {
        if (a == null || b == null) return a == null ? b : a;
        if (a.length() < b.length()) { //使得a永远是较长的那个
            String t = a;
            a = b;
            b = t;
        }
        int len1 = a.length(), len2 = b.length(), sum = 0, carry = 0;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len2; i++) {
            sum = carry + charToNum(a.charAt(len1 - 1 - i)) + charToNum(b.charAt(len2 - i - 1));
            carry = sum / 36;
            sum %= 36;
            if (sum >= 10) {
                sb.insert(0, (char)(sum - 10 + 'a'));
            } else {
                sb.insert(0, sum);
            }
        }
        for (int i = len2; i < len1; i++) {
            sum = carry + charToNum(a.charAt(len1 - 1 - i));
            carry = sum / 36;
            sum %= 36;
            if (sum > 10) {
                sb.insert(0, (char)(sum - 10 + 'a'));
            } else {
                sb.insert(0, sum);
            }
        }
        if (carry != 0) sb.insert(0, carry);
        return sb.toString();
    }

    public int charToNum(char c) {
        if (c >= 'a' && c <= 'z') return c - 'a' + 10;
        else return c - '0';
    }

    @Test
    public void test() {
        String a = "zzzz";
        String b = "zzzzzz";
        System.out.println(add(a, b));
    }

    public String mul(String a, String b) {
        if (a == null || b == null) return a == null ? b : a;
        if (a.length() < b.length()) { //使得a永远是较长的那个
            String t = a;
            a = b;
            b = t;
        }
        int len1 = a.length(), len2 = b.length(), sum = 0, carry = 0;
        int[] res = new int[len1 + len2], an = new int[len1], bn = new int[len2];
        for (int i = 0;  i < len1; i++) {
            an[i] = charToNum(a.charAt(i));
        }
        for (int i = 0;  i < len2; i++) {
            bn[i] = charToNum(b.charAt(i));
        }
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                res[i + j] += an[i] * bn[j];
            }
        }

        //进位
        StringBuilder sb = new StringBuilder();
        for (int i = len1 + len2 - 1; i >= 0; i--) {
                res[i] += carry;
                carry = res[i] / 36;
                res[i] /= 36;
                if (res[i] >= 10) {
                    sb.insert(0, (char)(res[i] - 10 + 'a'));
                } else {
                    sb.insert(0, res[i]);
                }
        }
        if (carry > 0) sb.insert(0, carry);
        return sb.toString();
    }

    @Test
    public void test1() {
        System.out.println(9999 * 9999);
        System.err.println(mul("9999", "9999"));
    }

}
